<template>
  <div>
    <!-- 页面头 -->
    <!-- <header class="header">
      <div class="header_left">
        <span @click="goBack">
          <i class="mintui mintui-back"></i>返回</span>
      </div>
      <div class="header_right">
        <span @click="goBack">取消</span>
      </div>
    </header> -->
    <mt-header class="plain" fixed>
      <mt-button slot="left" icon="back" @click="goBack">返回</mt-button>
      <mt-button slot="right" @click="goBack">取消</mt-button>
    </mt-header>
    <!-- 顶部导航 -->
    <div v-if="showTop" class="nav">
      <div class="nav_item" :class="{ active: level == 'LOW'}" @click="cut('LOW')">初级</div>
      <div class="nav_item" :class="{ active: level == 'MIDDLE'}" @click="cut('MIDDLE')">中级</div>
      <div class="nav_item" :class="{ active: level == 'HIGH'}" @click="cut('HIGH')">高级</div>
    </div>
    <div v-else class="nav"></div>
    <div v-if="loaded" class="top_pic">
      <!-- <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="playsinline" :options="playerOptions"></video-player> -->
      <img :src="result.coverurl" />
  </div>

      <div class="course_info">
        <div class="title">
          <span>课程简介</span>
          <span class="sup" @click="changeSup()">
            <img v-if="!isSup" src="@/assets/images/info/点赞.png">
            <img v-if="isSup" src="@/assets/images/info/已点赞.png">
            <span style="font-size: 12px;color: #666666;margin-left: 6px">{{supCount}}</span>
            <!-- <img style="margin-left: 12px" src="@/assets/images/课程_分享.png"> -->
          </span>
        </div>
        <div class="desc">
          <p v-if="result.content" v-clampy="row" @click="row = row==Infinity?4:Infinity">{{result.content}}</p>
        </div>
        <div class="author">
          <span>主讲人：{{result.teacher}}</span>
          <span>&nbsp;&nbsp;&nbsp;总课时数量:{{result.duration}}</span>
          <div class="time">学习进度:&nbsp;&nbsp;{{Math.round(result.progress*100)/100}}%</div>
        </div>
      </div>

      <div class="choose_button">
        <button class="button" @click="queryCourseDetail()">
          <label v-if="showTop" class="label">{{result.stagetxt || '开始报名'}}</label>
          <label v-else class="label">{{result.stage == 'EXAMINATION'?'课程完成':result.stagetxt}}</label>
        </button>
      </div>

      <!-- <div class="course_desc">
      <div class="title">
        <span>课程简介</span>
      </div>
      <div class="desc">
        <span>{{result.content}}</span>
      </div>
    </div> -->

      <div class="chapter">
        <mt-navbar v-model="selected" class="navbar">
          <mt-tab-item id="1">
            <span class="navbar-item">目录</span>
          </mt-tab-item>
          <mt-tab-item id="2">
            <span class="navbar-item">评论</span>
          </mt-tab-item>
        </mt-navbar>

        <!-- tab-container -->
        <mt-tab-container v-model="selected">
          <mt-tab-container-item id="1">
            <ul>
              <li class="period" v-for="(citem,cindex) in lessonList" :key="cindex" @click="play(citem)">
                <div class="title">
                  <img src="@/assets/images/课程_学习_章节_小.png" />
                  <span v-if="citem.stage=='CONTINUE'" :style="{color:CONTINUE}">{{citem.title}}</span>
                  <span v-else-if="citem.stage=='FINISHED'" :style="{color:FINISHED}">{{citem.title}}</span>
                  <span v-else>{{citem.title}}</span>
                </div>
                <div class="status">
                  <span v-if="citem.stage=='CONTINUE'" :style="{color:CONTINUE}">{{citem.stagetxt}}</span>
                  <span v-else-if="citem.stage=='FINISHED'" :style="{color:FINISHED}">{{citem.stagetxt}}</span>
                  <span v-else>{{citem.stagetxt}}</span>
                  <img v-if="citem.stage=='CONTINUE'" class="check" :style="{color:CONTINUE}" :src="citem.stage | getIcon">
                  <img v-else-if="citem.stage=='FINISHED'" class="check" :style="{color:FINISHED}" :src="citem.stage | getIcon">
                  <img v-else class="check" :src="citem.stage | getIcon">
            </div>
              </li>
            </ul>
          </mt-tab-container-item>

          <mt-tab-container-item id="2">

            <div class="comment_button">
              <button class="button" @click='inputDialogOpen'>
                <label class="label">发表评论</label>
              </button>
            </div>
            <mt-loadmore ref="loadMore" :auto-fill="false" :bottom-method="loadMore" @bottom-status-change="handleBottomChange" :bottom-all-loaded="allLoaded">
              <ul class="comment" style="min-height:100px">
                <li v-for="(item, index) in replyList" :key="index">
                  <div style="margin-top:14px;margin-bottom:12px;display: flex">
                    <div style="width:20%"><img style="width: 44px;height: 44px;border-radius: 50%;margin-left: 12px;" :src="personIcon"></div>
                      <div style="margin-left:12px;margin-right:12px; width:80%">
                        <div style="display: flex;justify-content: space-between">
                          <span style="font-size: 14px;color: #666666;">{{item.creatername || '匿名'}}</span>
                          <span style="font-size: 10px;color: #999999;">{{item.createtime | dateformat('YYYY-MM-DD HH:mm')}}</span>
                        </div>
                        <div style="margin-top:10px;text-align: left">
                          <span style="font-size: 12px;color: #666666;">{{item.content}}</span>
                        </div>
                      </div>
                    </div>
                </li>
              </ul>
            </mt-loadmore>
          </mt-tab-container-item>
        </mt-tab-container>
      </div>
      <div class="placehold"></div>
      <my-dialog ref="myDialog" v-bind="dialogConfig" v-on:confirm="apply" v-on:close="onCancel"></my-dialog>
      <my-dialog ref="inputDialog" v-bind="inputDialogConfig" v-on:confirm="appraise" v-on:close="onCancel">
        <div class="appraise" slot="content">
          <input class="appraise-text" v-model="appraiseContent" placeholder="请输入评论">
    </div>
      </my-dialog>
    </div>
</template>

<script type="text/ecmascript-6">
import api from '@/api/index'
import userApi from '@/api/user'
import {
  Const
} from '@/consts'
import utils from '@/utils'
import footerNav from '@/components/footer/footer'
import finished from '@/assets/images/课程_已完成.png'
import continueAble from '@/assets/images/课程_暂停.png'
import disAble from '@/assets/images/课程_不可播放.png'
import playAble from '@/assets/images/课程_播放.png'
import personIcon from '@/assets/images/personal/个人中心_完善资料_头像.png'
import Dialog from '@/components/dialog'
import {
  MessageBox,
  Toast
} from 'mint-ui'
export default {
  data () {
    return {
      FINISHED: '#1f88fe',
      CONTINUE: 'blue',
      finalScore: '',
      myProgress: '',
      mySchool: '',
      row: 4,
      introOpen: false,
      showTop: false,
      playsinline: true,
      isSup: false,
      supCount: '',
      appraiseContent: '',
      loaded: false,
      query: {},
      courseid: '',
      data: {},
      stage: '',
      result: {},
      logined: false,
      // playerOptions: {
      //   playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
      //   autoplay: false, // 如果true,浏览器准备好时开始回放。
      //   muted: false, // 默认情况下将会消除任何音频。
      //   loop: false, // 导致视频一结束就重新开始。
      //   preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
      //   language: 'zh-CN',
      //   aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
      //   fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
      //   sources: [{
      //     type: '',
      //     src: '' // 你的视频地址（必填）
      //   }],
      //   poster: '', // 你的封面地址
      //   // width: document.documentElement.clientWidth,
      //   notSupportedMessage: '此视频暂无法播放，请稍后再试', // 许覆盖Video.js无法播放媒体源时显示的默认信息。
      //   controlBar: {
      //     timeDivider: true,
      //     durationDisplay: true,
      //     remainingTimeDisplay: false,
      //     fullscreenToggle: true // 全屏按钮
      //   }
      // },
      selected: '1',
      chapter1: false,
      chapter2: false,
      chapter3: false,
      level: '',
      lessonList: [],
      replyList: [],
      pagesize: 10,
      pageno: -1,
      allLoaded: false,
      dialogConfig: {
        title: '温馨提示',
        content: '若您是符合国家规定能够享受课程补贴的人员,请注意每人每年只有一门课程有机会获得国家补贴,且必须在完成该课程有机会学习后通过职业认证方可享受此待遇,请谨慎选择',
        confirm: '确认选择',
        cancel: '我要再考虑一下'
      },
      inputDialogConfig: {
        title: '评论',
        confirm: '确定',
        casncle: '取消'
      }
    }
  },
  filters: {
    getIcon: function (value) {
      if (value === 'FREE') {
        return playAble
      } else if (value === 'FINISHED') {
        return finished
      } else if (value === 'CONTINUE' || value === 'EXAMINATION') {
        return continueAble
      } else if (value === 'DISABLED') {
        return disAble
      }
    }
  },
  mounted () {
    this.sysAlert()

    // alert(this.$route.params.id);
  },
  created () {
    // 判断登录状态
    this.logined = utils.checkUserLogined()
    // 获取课程详情
    this.getCourse()
    this.getInfoDetail()
  },
  computed: {
    personIcon () {
      return personIcon
    }
  },

  components: {
    footerNav,
    myDialog: Dialog
  },

  methods: {
    sysAlert () { },
    changeSup () {
      if (this.logined) {
        api.changeSup({
          params: {
            courseid: this.courseid
          }
        }).then(resp => {
          this.isSup = resp.result
          this.getSupCount()
        })
      } else {
        MessageBox.confirm('您还没有登录,现在要登录吗?').then(action => {
          this.$router.push({
            path: '/login'
          })
        })
      }
    },
    appraise () {
      this.$refs.inputDialog.close()
      api.addreply({
        params: {
          courseid: this.courseid,
          content: this.appraiseContent
        }
      }).then(resp => {
        Toast('提交成功,请等待管理员审核')
        this.replyList = []
        this.getReplyList(false)
      })
    },
    inputDialogOpen () {
      if (this.logined) {
        this.$refs.inputDialog.open()
        // document.querySelector('.video-player video').style.display = 'none'
        this.appraiseContent = ''
      } else {
        MessageBox.confirm('您还没有登录,现在要登录吗?').then(action => {
          this.$router.push({
            path: '/login'
          })
        })
      }
    },
    apply () {
      this.$refs.myDialog.close()
      api.startLearning({
        params: {
          courseid: this.courseid
        }
      }).then(resp => {
        if (resp.status === 'SUCCESS') {
          this.getCourse()
        }
      }).catch(resp => {
        Toast(resp.message)
      })
    },
    goBack () {
      let from = this.$route.query && this.$route.query.from
      if (from) {
        this.$router.push({
          path: '/' + from.replace(/-/g, '/')
        })
      } else {
        this.$router.push({
          path: '/index'
        })
      }
    },
    queryCourseDetail () {
      // document.querySelector('.video-player video').style.display = 'none'
      if (this.stage === 'SIGNUP' || this.stage == null) {
        if (this.logined) {
          // 我要报名
          console.log('点击了我要报名')
          this.$refs.myDialog.open()
        } else {
          MessageBox.confirm('您还没有登录,现在要登录吗?').then(action => {
            this.$router.push({
              path: '/login'
            })
          })
        }
      } else if (this.stage === 'CONTINUE') {
        for (let j in this.lessonList) {
          if (this.lessonList[j].stage === 'CONTINUE' || this.lessonList[j].stage === 'EXAMINATION') {
            console.log(this.lessonList[j])
            this.play((this.lessonList[j]))
          }
        }
      } else if (this.stage === 'EXAMINATION') {
        if (this.showTop) {
          if (this.myProgress < 2) {
            MessageBox.confirm('您尚未完善资料,是否现在完善资料').then(resp => {
              this.completeInfo()
            })
          } else {
            this.$router.push({
              path: '/exam/start',
              query: {
                courseId: this.courseid
              }
            })
          }
        } else {
          Toast('选修课无需考试')
        }
        // 开始考试
      } else if (this.stage === 'PRACTICAL') {
        // 实训报名
        this.$router.push({
          path: '/personal/school/list',
          query: {
            courseId: this.courseid
          }
        })
      } else if (this.stage === 'PARTICIPATION') {
        // 参与实训
        this.$router.push({
          path: '/personal/school/punchcard',
          schoolId: this.mySchool.schoolid
        })
      } else if (this.stage === 'FINALSCORE') {
        // 最终成绩
        this.getFinalScore().then(resp => {
          MessageBox('最终成绩为:' + this.finalScore)
        })
      }
    },
    completeInfo () {
      const msgText = '<div class="text-justify" style="line-height: 25px;">该信息将用于在通过考试后、报考学校时生成纸质报名表，若信息不符可能导致报名失败，请您依照真实情况填写。<div>'

      MessageBox.confirm(msgText, '温馨提示', {
        confirmButtonText: '我已知晓',
        cancelButtonText: '我要再考虑一下',
        closeOnClickModal: false,
        type: 'info'
      }).then(action => {
        //
        this.$router.push({
          path: '/personal/setting/complete',
          query: {
            from: 'index-courseInfo?courseid=' + this.courseid
          }
        })
      }).catch(() => {

      })
    },
    getCourse () {
      api.getCourse(this.initParams()).then(resp => {
        this.initPage(resp)
      })
    },
    getAnotherLevel (oldLevel) {
      api.getAnotherLevel({
        params: {
          courseid: this.courseid,
          courseleveltype: this.level
        }
      }).then(resp => {
        this.initPage(resp)
      }).catch(resp => {
        this.level = oldLevel
        Toast(resp.message)
      })
    },
    // 获取最终成绩的
    getFinalScore () {
      api.getFinalScore().then(resp => {
        console.log(resp)
        this.finalScore = resp.result.finalscore
      }).catch(resp => {
        Toast(resp.message)
      })
    },
    getLessonList () {
      api.getLessonList({
        params: {
          courseid: this.courseid
        }
      }).then(resp => {
        this.lessonList = resp.result
      })
    },
    getReplyList (firstLoad) {
      api.getReplyList({
        params: {
          courseid: this.courseid,
          pageno: this.pageno,
          pagesize: this.pagesize,
          order: 0
        }
      }).then(resp => {
        if (resp.result.length === 0) {
          this.allLoaded = true
        } else {
          this.replyList = this.replyList.concat(resp.result)
        }
        if (!firstLoad) {
          this.$refs.loadMore.onBottomLoaded()
        }
      })
    },
    getSupCount () {
      api.getSupCount({
        params: {
          courseid: this.courseid
        }
      }).then(resp => {
        this.supCount = resp.result
      })
    },
    getSupSign () {
      api.isSup({
        params: {
          courseid: this.courseid
        }
      }).then(resp => {
        this.isSup = resp.result
      })
    },
    getInfoDetail () {
      userApi.getInfoDetail().then((resp) => {
        const result = resp[Const.RESP_RESULT] || {}

        // 进度
        this.processMyProgress((result.mystatus || {}).stage)
        // 学校
        this.mySchool = result.myschool || {}
      }).catch((resp) => {
        // Toast(resp[Const.RESP_MESSAGE]);
        if (resp.statusCode == '200') {
          Toast(resp[Const.RESP_MESSAGE] || '获取信息失败')
        }
      })
    },
    processMyProgress (stage) {
      switch (stage + '') {
        case 'SIGNUP':
          this.myProgress = 0
          break
        case 'CONTINUE':
          this.myProgress = 1
          break
        case 'COMPLETE':
          this.myProgress = 1
          break
        case 'EXAMINATION':
          this.myProgress = 2
          break
        case 'PRACTICAL':
          this.myProgress = 3
          break
        case 'PARTICIPATION':
          this.myProgress = 4
          break
        case 'FINALSCORE':
          this.myProgress = 4
          break
        case 'GRADUATION':
          this.myProgress = 5
          break
        default:
          this.myProgress = 0
          break
      }
    },
    initPage (resp) {
      this.replyList = []
      this.row = 4
      this.pageno = -1
      this.allLoaded = false
      this.result = {}
      this.$nextTick(() => {
        this.result = resp.result
        if (this.result) {
          if (this.result.coursetype !== 'PUBLIC') {
            this.showTop = true
          }
          this.courseid = resp.result.courseid
          this.$route.query.courseid = this.courseid
          this.stage = resp.result.stage
          // this.playerOptions.poster = resp.result.coverurl
          // this.playerOptions.sources[0].src = resp.result.videourl || 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'
          this.level = this.result.courseleveltype
        }
        this.getLessonList()
        this.getSupCount()
        if (this.logined) {
          this.getSupSign()
        }
        this.loadMore(true)
        this.loaded = true
      })
    },
    initParams () {
      this.courseid = this.$route.query.courseid
      this.query = {
        params: {
          courseid: this.courseid
        }
      }
      return this.query
    },
    itemClick (index) {
      this.lessonList[index].open = !this.lessonList[index].open
      console.log(this.lessonList[index].open)
      // 强刷
      this.$forceUpdate()
    },
    cut (level) {
      if (level !== this.level) {
        let oldLevel = this.level
        this.level = level
        this.getAnotherLevel(oldLevel)
      }
    },
    loadMore (firstLoad) {
      if (firstLoad == '') {
        firstLoad = false
      }
      this.pageno = this.pageno + 1
      if (!this.allLoaded) {
        this.getReplyList(firstLoad)
      }
    },
    handleBottomChange (status) {
      console.log(status)
    },
    // 播放
    play (citem) {
      console.log(citem)
      if (citem.stage === 'FREE' || citem.stage === 'FINISHED' || citem.stage === 'CONTINUE') {
        this.$router.push({
          path: '/course/lesson',
          query: {
            lessonid: citem.lessonid,
            courseid: this.courseid
          }
        })
      } else if (citem.stage === 'DISABLED') {
        return null
      } else if (citem.stage === 'EXAMINATION') {
        MessageBox.confirm('<div style="height:100px;line-height:100px">是否开始章节测试?</div>').then(resp => {
          this.$router.push({
            path: '/course/lesson',
            query: {
              lessonid: citem.lessonid,
              courseid: this.courseid
            }
          })
        })
      }
    },
    onCancel () {
      // console.log(document.querySelector('.video-player video'))
      // document.querySelector('.video-player video').style.display = ''
    }
  }
}
</script>

<style lang="scss" scoped>
$scale: 1.2;
.header {
  display: flex;
  justify-content: space-between;
  padding-left: 16px;
  padding-right: 16px;
  padding-top: 16px;
  height: 45px;
  .header_left {
    span {
      font-size: 18px;
      color: #1f88fe;
    }
  }
  .header_right {
    span {
      font-size: 18px;
      color: #1f88fe;
    }
  }
}

.appraise {
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  .appraise-text {
    width: 100%;
    font-size: 14px;
    line-height: 28px;
  }
}

.nav {
  margin-top: 55px;
  display: flex;
  justify-content: center;
  .nav_item {
    width: 109px;
    font-size: 15px;
    color: #666666;
    height: 48px;
    line-height: 48px;
    border-bottom: 1px solid lightgrey;
  }
  .active {
    color: #1f88fe;
    border-bottom: 2px solid #1f88fe;
  }
  margin-bottom: 16px;
}

.top_pic {
  padding-left: 16px;
  padding-right: 16px;
  .video-js.vjs-playing .vjs-tech {
    pointer-events: auto;
  }
  img {
    width: 100%;
  }
}

p {
  text-indent: 2em;
}

.course_info {
  margin-top: 18px;
  padding-left: 14px;
  padding-right: 16px;
  .title {
    font-size: 15px * $scale;
    color: #000000;
    text-align: left;
    display: flex;
    justify-content: space-between;
    .sup {
      width: 50px;
      height: 24px;
      text-align: center;
    }
    img {
      width: 12px;
      height: 12px;
    }
  }
  .desc {
    margin-top: 10px;
    font-size: 12px * $scale;
    color: #666666;
    text-align: left;
    span {
      line-height: 5px;
    }
  }
  .author {
    margin-top: 9px;
    font-size: 12px * $scale;
    color: #333333;
    text-align: left;
    .time {
      font-size: 12px * $scale;
      line-height: 24px * $scale;
      color: #ffa133;
    }
  }
  .intro-open {
    width: 100%;
    text-align: center;
    color: #1f88fe;
    font-size: 16px;
    line-height: 20px;
    height: 20px;
  }
}

.choose_button {
  margin-top: 16px;
  height: 45px;
  .button {
    height: 45px;
    width: 160px;
    background-color: #1f88fe;
    border-radius: 5px;
    .label {
      font-size: 18px;
      color: #ffffff;
      text-align: center;
    }
  }
}

// .course_desc {
//   margin-top: 24px;
//   padding-left: 16px;
//   padding-right: 16px;
//   .title {
//     border-bottom: 0.5px solid #bbbbbb;
//     padding-bottom: 12px;
//     text-align: left;
//     span {
//       font-size: 16px;
//       color: #333333;
//     }
//   }
//   .desc {
//     margin-top: 18px;
//     text-align: left;
//     span {
//       font-size: 12px;
//       color: #333333;
//     }
//   }
// }
.chapter {
  margin-top: 18px;
  padding-left: 14px;
  padding-right: 16px;
  .navbar {
    border-top: 0.5px solid #e0e0e0;
    .navbar-item {
      font-size: 15px;
    }
  }
  .li {
    border-bottom: 0.5px solid #dddddd;
    .item {
      height: 44px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      img {
        width: 12px;
        height: 12px;
      }
      .title {
        margin-left: 12px;
        font-size: 15px;
        color: #333333;
      }
      .time {
        font-size: 15px;
        color: #999999;
      }
    }
  }
  .period {
    padding-top: 10px;
    padding-bottom: 10px;
    background-color: #f3f6f9;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      display: inline-table;
      margin-left: 8px;
      font-size: 12px * $scale;
      color: #666666;
      width: 70%;
      text-align: left;
      img {
        width: 10px;
        height: 10px;
        display: table-cell;
      }
      span {
        display: table-cell;
        width: 90%;
        text-align: left;
      }
    }
    .status {
      margin-right: 10px;
      white-space: nowrap;
      span {
        font-size: 10px * $scale;
        color: #999999;
      }
      img {
        margin-left: 8px;
        width: 12px;
        height: 12px;
      }
      .ing {
        font-size: 10px * $scale;
        color: #1f88fe;
      }
    }
  }
  .period:nth-child(n + 2) {
    margin-top: 12px;
  }
  .comment_button {
    margin-top: 16px;
    height: 30px;
    width: 100%;
    .button {
      background-color: #f2f2f2;
      border-radius: 5px;
      width: 100%;
      height: 30px;
      .label {
        font-size: 12px * $scale;
        color: #1f88f2;
        text-align: center;
      }
    }
  }
  .comment {
    margin-top: 16px;
    li {
      border: 1px solid #dddddd;
      border-radius: 5px;
    }
    li:nth-child(n + 2) {
      margin-top: 12px;
    }
  }
}
</style>
